#coding=utf-8
import cv2 as cv
import os
from SqlDB import myDB
import time
import tkinter as tk
from abhs import reallearn,memory
import datetime
from dateutil import rrule
maxheight=1000
maxweidth=1910
tridio=float(maxheight/maxweidth)
book=myDB('learn.db')
def getdeffrom(datebracket):
    today=datetime.date.today()
    endDay = datetime.date(datebracket[0],datebracket[1],datebracket[2])
    days = rrule.rrule(freq = rrule.DAILY,dtstart=today,until=endDay)
    return days.count()
losth=61.8
def GetScreenCenter():
    root = tk.Tk()
    return root.winfo_screenwidth()//2,root.winfo_screenheight()//2
def studio_resize(rows,cols):
    oridio=float(rows/cols)
    if oridio>tridio:
        rcols=maxheight/rows*cols
        rcols=int(rcols)
        return maxheight,rcols
    else:
        rrows=maxweidth/cols*rows
        rrows=int(rrows)
        return rrows,maxweidth
center_x, center_y = GetScreenCenter()
def studio_viewimg(filepath,code,title):
    mat=cv.imread(filepath) 
    sp=mat.shape
    rows=sp[0]

    cols=sp[1]
    rrows, rcols=studio_resize(rows, cols)
    cv.namedWindow(title,0)
    ncenter_y=center_y-25
    t_x, t_y = (center_x - rcols // 2), (ncenter_y - rrows // 2)
    img = cv.resize(mat, (rcols, rrows))
    cv.resizeWindow(title, rcols, rrows)
    cv.moveWindow(title, t_x, t_y)
    cv.imshow(title, img)
    keyin=cv.waitKey(code)
    cv.destroyAllWindows()
    return keyin
def studio_viewimglist(infolist,code):
    currentimginfo=infolist.get()
    walkflag=True
    while walkflag:
        path=currentimginfo[0]
        title=currentimginfo[1]
        keyin=studio_viewimg(path,code,title)
        if keyin==97:
            infolist.prev()
            currentimginfo=infolist.get()
        elif keyin==27:
            return False
        elif keyin==100:
            walkflag=infolist.next()
            currentimginfo=infolist.get()
        else:
            infolist.resetindex()
            return True
    return True
def simple_viewimg(filepath):
    src=cv.imread(filepath) 
    cv.namedWindow('input_image', cv.WINDOW_AUTOSIZE)
    cv.imshow('input_image', src)
    cv.waitKey(0)
    cv.destroyAllWindows()
#---------main------------------


def timesleep_plans(learncount):
    if learncount<4:
        sleeptime=13
    elif learncount<8:
        sleeptime=9
    else:
        sleeptime=6
    return sleeptime
def learntime(learncount,b_time):
    t=b_time
    if learncount<=1:
        t=1.5*b_time
    elif learncount<=3:
        t=1.75*b_time
    elif learncount<=6:
        t=2*b_time
    else:
        t=2.5*b_time
    return t
class Tmplist:
    def __init__(self,maxLen):
        self.body=[]
        self.currentindex=-1
        self.maxlen=maxLen
    def append(self,element):
        self.body.append(element)
        if len(self.body)>self.maxlen:
            del self.body[0]
        else:
            self.currentindex+=1
    def resetindex(self):
        self.currentindex=len(self.body)-1
    def get(self):
        if self.currentindex>=0:
            return self.body[self.currentindex]
        else:
            return None
    def next(self):
        currentmax=len(self.body)
        if self.currentindex>=currentmax-1:
            self.currentindex=currentmax-1
            return False
        else:
            self.currentindex+=1
            return True
    def prev(self):
        currentmax=len(self.body)
        if currentmax>0:
            if self.currentindex<1:
                self.currentindex=0
                return False
            else:
                self.currentindex-=1
                return True
        else:
            self.currentindex=-1
            return False
    def initself(self):
        self.body=[]
        self.currentindex=-1




def template():
    studyflag=True
    tmppicslist=Tmplist(6)
    while studyflag:
        current_time=time.time()
        studyflag=False
        for res in book.row_query("SELECT mid,path,lasttime,learncount FROM source"):
            mid=res[0]
            filename=res[1]
            filepath= os.path.join('source',filename)
            lastitme=res[2]
            learncount=res[3]
            title=str(mid)
            flag,newcount=False,0
            if not lastitme:
                flag,newcount=True,0
            else:
                delta_t=round((current_time-lastitme)/60,4)
                flag,newcount=reallearn(losth,delta_t,learncount)
            if flag:
                tmppicslist.append((filepath,title))
                print("添加{}".format((filepath,title)))
                studyflag=studio_viewimglist(tmppicslist, 0)
                if not studyflag:
                    break
                current_time=int(time.time())
                learncount=newcount+1
                book.update('source', ['lasttime','learncount'], ['mid'], (current_time,learncount,mid))
                break
def force_template():
    studyflag=True
    tmppicslist=Tmplist(6)
    while studyflag:
        studyflag=False
        for res in book.row_query("SELECT mid,path,lasttime,learncount FROM source"):
            mid=res[0]
            filepath=res[1]
            title=str(mid)
            tmppicslist.append((filepath,title))
            print("添加{}".format((filepath,title)))
            studyflag=studio_viewimglist(tmppicslist, 0)
            if not studyflag:
                break             
def readtime(mintime):
    if mintime<60:
        return "{}min".format(mintime)
    else:
        return "{}hours".format(round(mintime/64,2))

def gettargettime(losthp,maxlearntimes):
    studiodict={}
    learntimes=0
    passtime=1    
    while learntimes<maxlearntimes:
        flag,newcount=reallearn(losthp,passtime,learntimes)
        if flag:
            learntimes+=1
            studiodict[str(learntimes)]=learntimes
        passtime+=1
    return studiodict
    
def status(maxlearntimes):
    days=getdeffrom((2021,12,24))
    dstt=days*24*60
    tn=0
    ctlearntimes=0
    reallearnts=0
    timestamp=0
    for res in book.row_query("SELECT mid,path,lasttime,learncount FROM source"):
        learncount=res[3]
        if learncount>0:
            reallearnts+=1
            timestamp+=res[2]
        ctlearntimes+=learncount
        tn+=1
    supt=tn*maxlearntimes

    print("总条目：{}".format(tn))
    print("学习条目进度： {}%".format(round(reallearnts/tn*100, 4)))
    print("总复习进度： {}%".format(round(ctlearntimes/supt*100,4)))
    if reallearnts>0:
        avgcount=ctlearntimes/reallearnts
        current_time=time.time()
        lastitme=int(timestamp/reallearnts)
        delta_t=round((current_time-lastitme)/60,4)
        tsum=dstt+delta_t
        print(tsum)
        mure=memory(tsum,avgcount)
        print("截止目标天剩余记忆量 {}%".format(round(mure*reallearnts/tn,4)))        
    else:
        print("截止目标天剩余记忆量 0%")   

    
        
if __name__=='__main__':
    book=myDB('learn.db')
    while True:
        print("""
+-------------------------------+
|1|开始
|2|统览              
|3|统计信息
|4|测试
+-------------------------------+
exit:退出
请输入编号：
        """) 
        key=input('>>')
        if key=='exit':
            break
        elif key=='1':
            while True:
                template()
                tmpkey=input("finish,if forcemod[y/n]")
                if tmpkey=="y":
                    force_template()
                tmpkey=input("if restart[y/n]")
                if tmpkey=="n":
                    break
        elif key=='2':
            force_template()
        elif key=='3':
            #studict=gettargettime(losth, 12)
            status(12)
        elif key=='4':
            pass